package com.cci.kangdao.wechatOrder.service.impl;

import com.cci.kangdao.dao.model.WorkOrderT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.SmsTool;
import com.cci.kangdao.utilTool.SmsUtils;
import com.cci.kangdao.wechatOrder.constants.WeChatConstants;
import com.cci.kangdao.wechatOrder.dao.CRMSendSMSMsgTDao;
import com.cci.kangdao.wechatOrder.dao.WeChatSmsLinkTokenTDao;
import com.cci.kangdao.wechatOrder.exception.NotCheckException;
import com.cci.kangdao.wechatOrder.model.CRMSendSMSMsgT;
import com.cci.kangdao.wechatOrder.model.WeChatSmsLinkTokenT;
import com.cci.kangdao.wechatOrder.service.IWeChatNoticeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @description: 微信短信通知服务实现类
 * @author: zyf
 * @create: 2021-03-28
 */
@Service
public class WeChatNoticeServiceImpl implements IWeChatNoticeService {

    private Logger log = Logger.getLogger(this.getClass().getName());

    @Resource
    private CRMSendSMSMsgTDao msgTDao;
    @Autowired
    private RedisClientUtils redisClientUtils;
    @Autowired
    private PropertiesUtils propertiesUtils;
    @Resource
    private WeChatSmsLinkTokenTDao linkTokenTDao;

    @Override
    public void sendSmsNoticeNoWorkOrder(String phone, String message, String token) throws Exception {
        //发送短信
        String status = SmsUtils.sendMessage(phone, message);
        //获取链接过期时间
        Integer linkTime = Integer.parseInt(propertiesUtils.getPropertiesValue("redisSmsLinkCacheTime"));
        //插入数据到
        msgTDao.insert(getCrmMsgNoWorkOrder(phone, status, message));
        //生成过期时间
        String expireTime = LocalTimeUtil.getRealExpireTime(linkTime.longValue());
        //保存对应关系
        WeChatSmsLinkTokenT linkTokenT = getWeChatSmsLink(-1L, "", -1L, token, expireTime, WeChatConstants.SMS_LINK_FAILURE_TYPE);
        //
        linkTokenTDao.insert(linkTokenT);
        if (!"00".equals(status)) {
            log.error("服务商发送短信失败,原因=" + status);
            throw new NotCheckException("服务商发送短信失败");
        }


        //缓存地址并设置过期时间
        redisClientUtils.setObject(token, linkTokenT, linkTime);
        redisClientUtils.setObject("PHONE_TOKEN" + token, phone, 0);
    }

    @Override
    public void sendSmsNotice(WorkOrderT workOrderT,Long companyId,String message,String token) throws Exception {
        //发送短信
        String status = SmsUtils.sendMessage(workOrderT.getCustomerPhone(), message);

        //获取链接过期时间
        Integer linkTime = Integer.parseInt(propertiesUtils.getPropertiesValue("redisSmsLinkCacheTime"));
        //插入数据到
        msgTDao.insert(getCrmMsg(workOrderT,companyId,status,message));

        //生成过期时间
        String expireTime = LocalTimeUtil.getRealExpireTime(linkTime.longValue());
        //保存对应关系
        WeChatSmsLinkTokenT linkTokenT = getWeChatSmsLink(workOrderT.getId(),workOrderT.getOrderNoCrm(),companyId,token,expireTime,WeChatConstants.SMS_LINK_FAILURE_TYPE);
        //
        linkTokenTDao.insert(linkTokenT);
        if(!"00".equals(status)){
            log.error("服务商发送短信失败,原因="+status);
            throw  new NotCheckException("服务商发送短信失败");
        }


        //缓存地址并设置过期时间
        redisClientUtils.setObject(token,linkTokenT,linkTime);
    }

    @Override
    public String getSmsLinkMessageByOrder(WorkOrderT workOrderT,String token) throws Exception {
        //获取短信生成
        String link = propertiesUtils.getPropertiesValue("smsUploadLink");
        String orderNo = workOrderT.getOrderNo();
        String message  = String.format(WeChatConstants.SEND_SMS_LOCATION_MESSAGE,orderNo,link+token);
        return message;
    }


    @Override
    public String getSmsLinkMessageByCrm(String crmNo,String token) {
        String link = propertiesUtils.getPropertiesValue("smsUploadLink");
        String message  = String.format(WeChatConstants.SEND_SMS_CRM_LOCATION_MESSAGE,link+token);
        return message;
    }

    @Override
    public WeChatSmsLinkTokenT getSmsLinkTokenByToken(String token) throws Exception {
        return linkTokenTDao.selectByToken(token);
    }

    @Override
    public WeChatSmsLinkTokenT getSmsLinkTokenById(String id) throws Exception {
        if (StringUtils.isBlank(id)){
            throw  new NotCheckException("工单位置更新数据ID为空");
        }
        return linkTokenTDao.selectById(Long.parseLong(id));
    }

    @Transactional
    @Override
    public void saveSmsLinkToken(Long id,Long orderId, String crmOrderNo, Long companyId, String token, String expireTime, Integer type) throws Exception {

        WeChatSmsLinkTokenT linkTokenT = getWeChatSmsLink(orderId,crmOrderNo,companyId,token,LocalTimeUtil.getRealExpireTime(Long.parseLong(expireTime)),type);
        linkTokenT.setBindId(id);
        linkTokenTDao.insert(linkTokenT);

        //缓存地址并设置过期时间
        redisClientUtils.setObject(token,linkTokenT,Integer.parseInt(expireTime));
    }


    @Override
    public void updateSmsLinkTokenFlagByToken(String token) throws Exception {
        WeChatSmsLinkTokenT smsLinkTokenT = new WeChatSmsLinkTokenT();
        smsLinkTokenT.setToken(token);
        smsLinkTokenT.setUpdator(-1L);
        smsLinkTokenT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
        smsLinkTokenT.setDeleter(-1L);
        smsLinkTokenT.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
        int flag = linkTokenTDao.updateFlagByToken(smsLinkTokenT);
        if (flag == 0 ){
            //throw new NotCheckException("更新数据逻辑失败");
            log.error("更新数据逻辑失败");
            return;
        }
    }

    /**
     * 生成短信发送记录
     *
     * @param phone
     * @param status
     * @param message
     * @return
     */
    private CRMSendSMSMsgT getCrmMsgNoWorkOrder(String phone, String status, String message) {
        CRMSendSMSMsgT msgT = new CRMSendSMSMsgT();
        msgT.setOrderId(-1L);
        msgT.setCrmOrderNo("");
        msgT.setSendTime(LocalTimeUtil.getRealCurrentTime());
        msgT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        msgT.setCreator(-1L);
        msgT.setContent(message);
        msgT.setSendType(1);
        msgT.setStatus("00".equals(status) ? 1 : 0);
        msgT.setRemark(status);
        msgT.setCustomerPhone(phone);
        msgT.setIsHaveWorkOrder(0);
        return msgT;
    }

    /**
     * 生成短信发送记录
     * @param order
     * @param companyId
     * @param status
     * @return
     */
    private CRMSendSMSMsgT getCrmMsg(WorkOrderT order, Long companyId, String status, String message){
        CRMSendSMSMsgT msgT =  new CRMSendSMSMsgT();
        msgT.setOrderId(order.getId());
        msgT.setCrmOrderNo(order.getOrderNoCrm());
        msgT.setSendTime(LocalTimeUtil.getRealCurrentTime());
        msgT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        msgT.setCreator(-1L);
        msgT.setContent(message);
        msgT.setSendType(1);
        msgT.setStatus("00".equals(status)?1:0);
        msgT.setRemark(status);
        msgT.setCustomerPhone(order.getCustomerPhone());
        msgT.setCustomerName(order.getCustomerName());
        msgT.setIsHaveWorkOrder(order.getId() == 0?0:1);
        msgT.setCompanyId(companyId);
        return msgT;
    }

    /**
     *  获取工单对象
     * @param orderId
     * @param crmOrderNo
     * @param companyId
     * @param token
     * @param expireTime
     * @param type
     * @return
     */
    private WeChatSmsLinkTokenT getWeChatSmsLink(Long orderId,String crmOrderNo,Long companyId,String token,String expireTime,Integer type){
        WeChatSmsLinkTokenT linkTokenT = new WeChatSmsLinkTokenT();
        linkTokenT.setCompanyId(companyId);
        linkTokenT.setOrderId(orderId);
        linkTokenT.setCrmOrderNo(crmOrderNo);
        linkTokenT.setToken(token);
        linkTokenT.setExpireTime(expireTime);
        linkTokenT.setType(type);
        linkTokenT.setVersion(0);
        linkTokenT.setFlag(0);
        linkTokenT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        return linkTokenT;
    }


    @Override
    public void updateTokenStatusByBindId(Long id,Integer flag) {
        linkTokenTDao.updateFlagByBindId(id,flag);
    }

    @Override
    public WeChatSmsLinkTokenT selectTokenByTokenAndStatus(Long id, String token, Integer status) {
        return linkTokenTDao.selectByTokenAndFlagAndId(id,status);
    }
}
